﻿using System;
using System.Collections.Concurrent;
using MediatR;
using MediatR.RequestHandlerFactory;

namespace SW.DDD.Application.Query
{
    internal class FindHandlerFactory : IRequestHandlerFactory
    {
        private static readonly ConcurrentDictionary<Type, Type> _typeCache = new ConcurrentDictionary<Type, Type>();

        private readonly IServiceProvider _serviceProvider;

        public FindHandlerFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public IRequestHandler<TRequest, TResponse>? Create<TRequest, TResponse>() where TRequest : IRequest<TResponse>
        {
            var commandType = typeof(TRequest);
            if(_typeCache.TryGetValue(commandType, out var type))
                return (IRequestHandler<TRequest, TResponse>)_serviceProvider.GetService(type);

            if(!commandType.IsGenericType || commandType.GetGenericTypeDefinition() != typeof(Find<,,>))
                return null;

            var genericHandlerType = typeof(FindHandler<,,>);
            var gArgs = commandType.GetGenericArguments();
            type = genericHandlerType.MakeGenericType(gArgs);
            _typeCache[commandType] = type;
            return (IRequestHandler<TRequest, TResponse>)_serviceProvider.GetService(type);
        }
    }
}
